package com.wjw.redis.stream.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wjw.redis.stream.model.BaseMsgEvent;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author wjwei
 */
@Slf4j
@Component
public class EventSubscriber implements InitializingBean, ApplicationContextAware {
    private static RedissonClient redissonClient;
    private static ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        new Thread(() -> {
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("redis-block-test");
            while (true) {
                try {
                    String take = blockingDeque.take();
                    log.info("读取队列消息：{}", take);
                    BaseMsgEvent baseMsgEvent = JSON.parseObject(take, new TypeReference<BaseMsgEvent>() {
                    }.getType());
                } catch (InterruptedException e) {
                    log.error("获取消息异常", e);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.error("sleep异常：", e);
                }
                log.info("redissonClient:{}", redissonClient);
                log.info("applicationContext:{}", applicationContext);
            }
        }).start();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        redissonClient = applicationContext.getBean(RedissonClient.class);
        applicationContext = applicationContext;
    }
}
